package com.meiyuetao.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by
 */
public class FileUploadUtil {

    /**
     * 上传图片文件至服务器保存
     *
     * @param fileName    文件名，不带后缀
     * @param inputStream 文件输入流
     * @return 若上传成功，则返回文件的url，若失败则为空
     */
    public static String uploadPic(String fileName, InputStream inputStream) {
        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, fileName).build();
        HttpPost httpPost = new HttpPost("http://img5.iyoubox.com/PutLocalFile.aspx");
        httpPost.setEntity(httpEntity);
        CloseableHttpResponse httpResponse = null;
        String bkmd5 = "";
        try {
            httpResponse = HttpClients.createDefault().execute(httpPost);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                String responseBody = EntityUtils.toString(httpResponse.getEntity());
                System.out.println("Upload complete, response: " + responseBody);
                if (responseBody.startsWith("1+")) {
                    bkmd5 = responseBody.substring(2);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                    return bkmd5;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
